﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace JasLib.Interop.Win32
{
    /// <summary>
    /// This DLL file is being phased out in Windows 7 (and Windows Server 2008) or later,
    /// and Microsoft appears to be switching its exports to KERNEL32, with a "K32" function name prefix.
    /// It is provided for backwards compatibility.
    /// </summary>
    [Obsolete]
    public static partial class PSAPI
    {
        [DllImport(Constants.ModuleNames.PSAPI, EntryPoint = "GetPerformanceInfo", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool GetPerformanceInfo(
            [Out] out PERFORMANCE_INFORMATION pPerformanceInformation,
            [In] uint cb);

        [DllImport(Constants.ModuleNames.PSAPI, EntryPoint = "GetProcessImageFileNameW", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Winapi, SetLastError = true)]
        public static extern uint GetProcessImageFileName(
            [In] HANDLE hProcess,
            [Out] StringBuilder lpFileName,
            [In] uint nSize);

        /// <summary>
        /// Safe wrapper for the GetProcessImageFileName Win32 function that throws an exception on failure.
        /// </summary>
        public static string GetProcessImageFileName(HANDLE hProcess, int iTryBufferLength = Constants.MAX_PATH)
        {
            StringBuilder sb = new StringBuilder(iTryBufferLength);
            sb.Length = (int)GetProcessImageFileName(hProcess, sb, (uint)sb.Capacity);
            if (sb.Length == 0 && KERNEL32.GetLastError() != Win32ErrorCode.ERROR_SUCCESS)
                throw new Win32Exception();
            return sb.ToString();
        }
    }
}
